/**
 * 通用的SSH连接
 * Created by zengxm on 12/21/2016.
 */
var Client = require('ssh2').Client
const NodeSSH=require("node-ssh")
const assert=require('assert')
const fs=require('fs')
const path=require('path')

/**
 * ssh2连接
 * @param host
 * @param onReady
 * @returns {*|Client}
 */
exports.connect2=(host, onReady)=>{
    const client=new Client()
    client
        .on("ready", onReady)
        .on("error",function(err){
            console.log("\tssh %s@%s failed:%s".red, host.user,host.ip,err.message)
            client.end()
        })
        .connect({
            host: host.ip,
            port: host.port,
            username: host.user,
            password: host.password
        })
    ;
    return client;
}

/**
 * 使用node-ssh连接
 * @param host
 * @param onReady
 */
exports.connect=(host, onReady)=>{
    const ssh=new NodeSSH()
    ssh.connect({
        host: host.ip,
        port: host.port,
        username: host.user,
        password: host.password
    }).then(onReady, function (err) {
        console.log("\tssh %s@%s failed:%s".red, host.user,host.ip,err.message)
        ssh.dispose();
    })

    return ssh;
}

/**
 * 上传文件
 * @param ssh       node-ssh连接对象（使用connect方法创建）
 * @param entity    包含以下属性：
 *                   {
 *                      local   本地文件路径
 *                      remote  远程文件存放目录
 *                      filename    远程文件名（最终远程文件问：{remote}/{filename}），如果为空则与本地文件同名
 *                      replace 当远程文件存在时，是否覆盖
 *                      onStep:Function 上传进度监听：
 *                                  function(< integer >total_transferred, < integer >chunk, < integer >total) - Called every time a part of a file was transferred
*                    }
 * @param onResult
 */
exports.upload=(ssh,entity,onResult)=>{
    assert(ssh != null, "ssh connection must not be null")
    assert(entity && entity.local, "entity.local must be string")
    assert(entity && entity.remote, "entity.remote must be string")
    assert(fs.existsSync(entity.local), "file ${entity.local} does not exist")
    //构建完整的目录
    const remoteFile = entity.remote+"/"+(entity.filename?entity.filename:path.basename(entity.local))

    const conn= ssh.connection?ssh.connection:ssh   //判断是node-ssh还是SSH2对象

    //详见https://github.com/mscdex/ssh2-streams/blob/master/SFTPStream.md
    conn.fastPut(
        entity.local,
        remoteFile, {
            step:entity.onStep
        },
        onResult
    )
}